/**
 * 登录模块，提供登录相关业务功能
 * 
 * @Date: 2015-6-16
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */
define(["jquery", "datagridServ","bsMsgServ", "ckeditor-jquery", "init","btnServ","bsDropDownMenu","formServ","codeDef",'uploadfiles',
	"panelUtil","buttonEvent",'moment','bootstrap-datetimepicker','bootstrap-datetimepicker.zh-CN','dateUtil'],
		function($,datagridServ, bsMsgServ, ckeditor,init, btnServ,bsDropDownMenu,formServ,codeDef,uploadfiles,
			panelUtil,buttonEvent,moment,datetimepicker,datetimepickerLang,dateUtil) {

			'use strict';

			var _bizProto,_buttonConfig,_moduleConfig,_defaultConfig,
				//锚记datagrid目标元素
				$dg,$typegrid,$detailgrid,
				//初始化后的datagrid dom对象
				$grid,
				//编辑弹窗对象及弹窗按钮对象
				$edit_window,window_btn,
				$edit_window_height=700,$edit_window_width=900,
				//设置密码弹窗对象及按钮对象
				$password_window,password_btn,
				//业务表单对象
				$form,selectedRecord,
				//部门选择框字段
				$deptNameField, $deptIdField,formEl, formData = 0,
				saveUrl = '/docdetail/save.action',
				
				docdetailEditUrl='/document/query/getPage.action?code=bsDocdetailDlg',
				
				//获取附件列表url
				uploadListurl = '/upload/query/getInitListDomain.action',
				//页面根节点dom元素
				rootid = 'bs-doc-manage',
				
				//弹窗根节点dom元素
				edit_window_id = 'bs-doc-detail-win',
				
				//模块代码
				moduCode = 'docdetail',
				
				//模块配置
				_moduleConfig,
				
				//ckeditor dom对象
				editor,
				
				//ckeditor id
				ck_id = 'lob_contents',
				
				//分类编码
				selectedType,
				
				//列表页面传递参数
				mainParam
				
				
				
			var public_method = {
				
				/**
				 * 在列表页面替换打开
				 */
				replaceInit:function(_options){
					if(_options){
						mainParam = _options;
						var _c = $('#'+rootid + ' .list-detail');
						if(_c.length==1){
							_c.empty();
							_c.load('/'+init.getSite() +docdetailEditUrl);							
						}
					}
				}
				,
				init:function(doc){
					private_method.init(doc);
				},
				destroy:function(){
					
					
					window_btn = $('#'+ rootid +' .btn-container button')
					if(window_btn.length>0){
						window_btn.unbind('click')
					}
					
					
					var file_btn = $('#'+rootid +' .archive-btn')
					if(file_btn.length>0){
						file_btn.unbind('click');
						
					}
					
					var _instance = CKEDITOR.instances[ck_id]
					if(_instance){ 
					    _instance.destroy(true); 
					}
					_moduleConfig = null;		
					
				},
				/**
				 * 
				 * @param _options.grid	  文档列表
				 * @param _options.flag	  新增或编辑标志
				 * @param _options.window	编辑窗口
				 * @param _options.selectedType 分类id
				 * @param _options.evt		触发事件
				 */
				pageShow:function(_options){					
					
					selectedType = _options.selectedType;
					var _df = {
						grid:$('#'+rootid + ' .dg-list'),
						window:$('#'+edit_window_id),
						onClose:public_method.destroy
					}
					var _default = $.extend({},_df,init.getWidthHeight(),_options)
					
					
					var _url
					var _config = init.getBizConfig({bizcode:moduCode});
					
					var _code
					if(_config.addition_param){
						_code = $.parseJSON(_config.addition_param)						
					}
					
					if(_code && _code.module){
						_url = '/'+init.getSite() +docdetailEditUrl +'?module='+_code.module
					}else{
						_url = '/'+init.getSite() + docdetailEditUrl
					}
					  
					
					_default = $.extend({},_default,
						{						
							href:_url,					
							existCheckElement:'form'					
						}
					)
					
					
					datagridServ.bsWindowEdit(_default);
					if(_options.evt)
						$(_options.evt.currentTarget).removeClass('disabled');
				}
				
			}

			var util = {
				getConfig:function(){
					
					if(!_moduleConfig){
						_moduleConfig = init.getBizConfig({bizcode:moduCode})
					}
					return _moduleConfig
				}
			}
			
			var private_method = {
				
				
				
				init : function(_options) {
					if (window.console) {
					console.info('bsDocdetailEdit loaded...');
					}
					
					var _config = util.getConfig() ;				
					
					
					//初始化编辑页面按钮
					private_method.initDetailEditBtn();
					
					//初始化时间控件
					private_method.initDatepicker();
					
					//定位分类和明细dom对象
					$typegrid = $('#'+rootid + ' .tg-tree');
					$grid = $('#'+rootid + ' .dg-list');
					
					//定位form对象
					$form = $('#'+rootid + ' .main-form')
					
					//清除原有form数据
					$form.form('clear');
					
					
					selectedRecord = mainParam.row					
					
					
					if(!selectedRecord){
						//判断用户信息
						selectedRecord = {}
												
					}					
					
					//判断用户名是否为空
					if(!selectedRecord.public_user_name){
						var usr = init.getCurrentUser();				
						if(usr){						
							selectedRecord.public_user_id = usr.id;						
							selectedRecord.public_user_name = usr.name;						
							selectedRecord.public_dept_id = usr.deptid;
							selectedRecord.public_dept_name = usr.deptName;							
						}
					}
					
					//初始化发布时间					
					if( !selectedRecord.public_date){
						selectedRecord.public_date = dateUtil.getDateValue({format:'yyyy-MM-dd hh:mi:ss'});
					}
					$form.form('load',selectedRecord);
					
					
					//初始化ckeditor
					private_method.initCkeditor(selectedRecord)	
					
					var _queue = $('#'+rootid + ' #queue')
					var _file = $('#'+rootid + ' #file_upload')
					
					
					private_method.initUpload();
					
					//绑定按钮事件
					private_method.bindBtnEvent();
					
					
					//初始化附件
					private_method.initArchive();
				},	
				
				//获取附件上传参数
				getUploadParam:function(){
					//附件参数处理
					var _bizcode = mainParam.selectedType.bizcode
					var _data = {
						bizcode:(_bizcode?_bizcode:moduCode)
					}
					//业务id处理
					var _idEl = $('#'+rootid +' #id')
					
					var _id
					if(_idEl.length ==1){
						
						
						var _tmpValue = $(_idEl).val()
						
						if(!_tmpValue || _tmpValue==''){
							//id为空,赋值临时id
							var _date = new Date();
							_id = 'TMP' + _date.getFullYear()+''+(_date.getMonth()+1)+''+_date.getDate()+'' +_date.getMilliseconds();
							var _tmpid = $('#'+rootid +' #tmpid')
							$(_tmpid).val(_id)
							$(_idEl).val(_id)
						}else{
							//id不为空，取id值
							_id = _tmpValue;
						}
					}
					
									
					_data.bizno=_id;	
					
					return _data;
					
				}
				,
				
				initUpload:function(){
					
					var _data = private_method.getUploadParam();
					
					//初始化上传附件组件
					uploadfiles.init({
						data:_data,							
						queue_id: rootid + ' #queue',
						file_id : rootid + ' #file_upload',
						rootPath: '/'+init.getSite(),
						rootid  : rootid,
						auto    : true,
						queueComplete : private_method.upload_success,
						uploadComplete: private_method.uploadSuccess
					});
					
				}
				,
				
				initCkeditor:function(selectedRecord){
					//初始化ck
					var _instance = CKEDITOR.instances[ck_id]
					if(_instance){ 
					    _instance.destroy(true); 
					}
					CKEDITOR.replace(ck_id,init.getLobConfig());
					
					//初始化ckeditor
					if(selectedRecord ){
						var _contents
						if(selectedRecord.lob_contents){
							_contents = selectedRecord.lob_contents;							
						}else{
							if(selectedRecord.lobid){
								_contents = init.getLobContents(selectedRecord.lobid);
							}
						}
						
						if(_contents){
							CKEDITOR.instances[ck_id].setData(_contents);
						}
					}
				}
				,
				initDetailEditBtn:function(){
					if(window.console){
						console.log(' detail edit button init ...')
					}
					var _btn = bsDropDownMenu.getMenu({bizcode:moduCode,btnType:'edit',bizType:2});
					
					if(_btn){
						var _c = $('#'+rootid + ' .btn-container')
						if(_c.length>0){
							_c.empty();
							_c.append(_btn);
						}
					}
					
				}
				
				,
				
				/**
				 * 初始化时间控件
				 */
				initDatepicker:function(){
				
					var _start = $('#'+rootid + ' #public_date')
					var _end = $('#'+rootid + ' #unpublic_date')
					
					var _param ={
						language:  'zh-CN',
						format: "yyyy-mm-dd hh:ii:ss",
						autoclose: true,
						minView: "month",
						maxView: "decade",
						todayBtn: true,
						pickerPosition: "bottom-left"
					}
					
					if(_start.length==1){
						if(window.console){
							console.log( ' start length: ' + 1)
						}
						_start.datetimepicker(_param);
						
						if(_end.length==1){
							if(window.console){
								console.log( ' start length: ' + 1)
							}
							_start.on("click",function(ev){
								_start.datetimepicker("setEndDate", _end.val());
							})
							
							_end.datetimepicker(_param)
								.on("click", function (ev) {
									_end.datetimepicker("setStartDate", _start.val());
								})
						}
					}				
				}
				,
				/**
				 * 初始化附件信息
				 * @param _options.bizcode	业务编码
				 * @param _options.bizno	业务id
				 * 
				 */
				initArchive:function(){
					
					var _el = $('#' + rootid + ' #archive');
					_el.empty();
					/**
					 * 根据审核状态判断是否显示按钮栏
					 */
					var showToolBar = true
					
					if(buttonEvent.checkAuditStatus({editWindow:rootid})){
						showToolBar = false
					}						
					
					var _data = private_method.getUploadParam();
					
					var _param = {
						url:'/'+init.getSite()+uploadListurl,
						data:{condition:_data},
						type: 'post',
						success:function(data){
							if(window.console){
								console.log(' archive init ...')
							}
							var _html ='';
							if(data && data.rows){
								_html = '<ul>'
								$.each(data.rows,function(i,o){
									if(o.filename){
										_html += '<li><span>'+o.filename+'</span>'
										         
										var _name = o.filename.split('.');
										if(_name.length>0){
											var _extname = _name[_name.length-1];
											var _type = '';
											switch(_extname){
												case 'doc':
													_type = _extname;
													break;
												case 'docx':
													_type = _extname;
													break;
//												case 'xls':
//													_type = _extname;
//													break;
//												case 'xlsx':
//													_type = _extname;
//													break;
												default:
													
											}
										}
										
										if(_type){
											_html += '<a class="archive-preview archive-btn" btn-type="preview" aid="'+o.id+'" >'+'        预览' +'</span></a>';
											
										}
										
										_html += '<a class="archive-info archive-btn" btn-type="download" aid="'+o.id+'">'+'        下载'+'</a>' +
										'<a class="archive-remove archive-btn" btn-type="remove" aid="'+o.id+'"><span style="color:red">'+'        删除' +'</span></a>' +
											'</li>';	
									}
								})
								
								_html +='</ul>'
							}
							
							
							_el.append(_html);
							
							//绑定下载点击事件
							var file_btn = $('#'+rootid + ' .archive-info')
							if(file_btn.length>0){
								file_btn.unbind('click')
								file_btn.bind('click',	btnEvent.downloadFile)
							}
							
							//绑定预览点击事件
							var file_btn = $('#'+rootid + ' .archive-preview')
							if(file_btn.length>0){
								file_btn.unbind('click')
								file_btn.bind('click',	btnEvent.previewFile)
							}
							
							//绑定下载点击事件
							var file_btn = $('#'+rootid + ' .archive-remove')
							if(file_btn.length>0){
								file_btn.unbind('click')
								file_btn.bind('click',	btnEvent.removeFile)
							}
							
						}
					}
					
					$.ajax(_param);
				},
				upload:function(){
					uploadfiles.upload()					
				},				
				
				//绑定按钮事件
				bindBtnEvent:function(){
					
					
					
					window_btn = $('#'+rootid + ' .relate-link')
					if(window_btn.length>0){
						window_btn.unbind('click')
						window_btn.bind('click',private_method.function_btn_listenner)
					}
					
					
					
				},	
				
				//功能按钮监听函数
				function_btn_listenner:function(e){	
					init.applyBtnEvt({btnEvt:e,btnConfig:btnEvent});									
				}
				,
				/**
				 * 获取表单验证规则
				 */
				getFormRule:function(){
					var rules = {
						rules:{
							name: 'required',
							public_dept_name:'required',
							public_user_name:'required',
							public_date:'required'
						}
						,
						messages:{
							name: '文档标题不允许为空',
							public_dept_name:'科室不允许为空',
							public_user_name:'人员不允许为空',
							public_date:'发布时间不允许为空'
						}
					}
					
					return rules;
				}
				
				,
				upload_success:function(file,data){
					if(window.console)
						console.log(data);
						
					var _bizcode = mainParam.selectedType.bizcode
					var _data = {
							bizcode:(_bizcode?_bizcode:moduCode)
						}
					
					var _id =$('#'+edit_window_id + ' #id').val()
					if(_id){
							_data.bizno=_id	}
					
					private_method.initArchive(_data);
					bsMsgServ.msgSlide('文件上传成功')
				},
				
				uploadSuccess:function(file,data,response){
					
					var _bizcode = mainParam.selectedType.bizcode
					var _data = {
							bizcode:(_bizcode?_bizcode:moduCode)
						}
					
					var _id =$('#'+edit_window_id + ' #id').val()
					if(_id){
							_data.bizno=_id	}
					
					private_method.initArchive(_data);
					bsMsgServ.msgSlide('文件上传成功')
				},
				uploadErr:function(){
					
				}
				
				,
				//附件页面预览
				initArchiveContent:function(data){
					if(window.console){
						console.log(' archiveContent loading ...')
					}
					if(data){
						
						if(data.typeName){
							//文档类型
							var contentHeaderEl = $('span.doctype')
							
							if(contentHeaderEl.length==1){
								$(contentHeaderEl).html('文档类别:'+data.typeName)
							}
						}
						
						//发布人员
						var public_dept_user
						var contentHeaderEl = $('span.public_dept_user')
					
						if(contentHeaderEl.length==1){
							if(data.public_dept_name){
								public_dept_user = '发布人: ' +data.public_dept_name
								if(data.public_user_name){
									public_dept_user += ' ' + data.public_user_name;
								}
							}else{
								if(data.public_user_name){
									public_dept_user = '发布人: ' +data.public_user_name
								}
							}
							if(public_dept_user)
							$(contentHeaderEl).html(public_dept_user)
						}
						
						if(data.public_date){										
											
							//发布时间										
							var contentEl = $('span.public_date')
							if(contentEl.length==1){
								$(contentEl).html(data.public_date)
							}
						}
						
						//附件内容
						var _p = {
							url	: '/portal/getContentArchive',
							data:{docid:data.id,bizcode:data.typeCode},
							success:function(_data){
								
								var _h = '';
								if(_data && _data.rows ){
									if((_data.rows)[0]){										
									
										var t = (_data.rows)[0]
										//文档内容										
										var contentEl = $('div.content-text')
										if(contentEl.length==1){
											_h = t.content;											
										}										
									}
									
									
									
									//文档附件
									var _el = $('.archive-container');
									var _html ='<h3>';								
									$.each(_data.rows,function(i,o){
										var _tmp = '附件: <a class="archive-info" aid="'+o.id+'">'+o.fileName+'</a>';
										
										_html = _html?_html+_tmp:_tmp;									
									})												
											
									
									_h = _html + '</h3>';
									
									
									var _content = $('#'+rootid + ' .modal-body')
									_content.html(_h)	
									var _m = $('#'+rootid + ' #doc-preview');
									_m.modal('show');
									
									//绑定点击事件
									var file_btn = $('#'+rootid  +' .archive-info')
									if(file_btn.length>0){
										file_btn.unbind('click')
										file_btn.bind('click',	private_method.downloadFile)
									}
								}
							}
							,
							error:function(){
								
								
							}						
						}
						$.ajax(_p);
					}
				}
			}
			var btnEvent = {
				// 提交form
				editSave : function(e) {
					
					var _f = $('#'+rootid + ' .main-form')
					if(
						!formServ.validateForm({
							form:_f,
							rules:private_method.getFormRule()
						})
					){
						bsMsgServ.errorSlide('请填写表单内容');
						//释放按钮禁用状态
						$(e.currentTarget).removeClass('disabled');
						return
					}
					
										
					
					if(buttonEvent.checkAuditStatus({editWindow:rootid})){
						bsMsgServ.errorSlide('已审核记录无法修改记录内容');
						$(e.currentTarget).removeClass('disabled');
						return
					}						
					
					
					var formData = formServ.getDataObj({
								form : $('#'+rootid + ' .main-form')
							});
					
					//设置分类编码
					if(mainParam.selectedType){
						formData.typeId = mainParam.selectedType.id;
					}
					
					//流程信息
					if(_moduleConfig.flowid){
						formData.flowid = _moduleConfig.flowid
						formData.fullBizcode = _moduleConfig.fullBizcode
					}
					
					//获取ckeditor值
					var _instance = CKEDITOR.instances[ck_id];
					
					if(_instance){
						var _data = _instance.getData();
						
						if(_data){
							formData.lob_contents = _data;	
						}
					}
					//检测id是否合法，避免tmpid影响保存
					var idVal = formData.id;
					if(idVal){
						if(idVal.indexOf('TMP')>=0){
							formData.id = null;
						}
					}
					
					//业务编码
					if(!formData.bizcode){
						var _bizcode = mainParam.selectedType.bizcode
						formData.bizcode = (_bizcode?_bizcode:moduCode)
					}
					$.ajax({
						url:'/'+init.getSite()+'/docdetail/save.action',
						data:$.toJSON(formData),
						contentType:'appliction/json;charset=utf-8',
						type:'post',
						dataType:'json',
						success:function(data){
							if(data){
								
								//刷新grid
								$('#'+rootid + ' .dg-list').datagrid('reload')
								//刷新form
								$('#'+rootid + ' .main-form').form('load',data);
								
								//刷新附件上传组件
								private_method.initUpload();
								
								//初始化附件显示
								private_method.initArchive();
							}
							bsMsgServ.msgSlide(codeDef.getConfig({
								type:'operate',
								code:'success'
							}))
							
							$(e.currentTarget).removeClass('disabled');
						}
						,
						failure:function(){
							bsMsgServ.msgSlide(codeDef.getConfig({
								type:'operate',
								code:'error'
							}))
							$(e.currentTarget).removeClass('disabled');
						}
					})
									
				},				
				
				//
				editCancel : function(e) {
//					$('#'+edit_window_id).window('close');
//					$('#'+edit_window_id).empty();
					$(e.currentTarget).removeClass('disabled');
					
					if(mainParam && mainParam.callback){
						public_method.destroy();
						mainParam.callback();
					}
				}
				,
				downloadFile:function(e){
					var _btn = $(e.currentTarget)
					
					var _id = _btn.attr('aid')
					
					var _url = '/'+init.getSite() +'/upload/downloadFileTest.action'
					var form = $("<form>");
					form.attr('style','display:none');
					form.attr('target','');
					form.attr('method','post');
					form.attr('action',_url);
					var input1 = $("<input>");
					input1.attr('type','hidden')
					input1.attr('name','id')
					input1.attr('value',_id);
					$('body').append(form);
					$(form).append(input1);
					
					form.submit();
					form.remove();
				}
				
				,
				removeFile:function(e){
					var _btn = $(e.currentTarget)
					
					var _id = _btn.attr('aid')
					
					if(_id){
						$.messager.confirm('警告', '确定执行删除操作?', function(r){
						
							if( r){	
								var _url = '/'+init.getSite() +'/upload/del.action';
								$.ajax({
									url:_url,
									data:{id:_id},
									success:function(data){
										if(data && data.status=='success'){
											private_method.initArchive();
											bsMsgServ.msgSlide();
										}else{
											bsMsgServ.warnSlide();
										}
									}
									,
									error:function(){
										bsMsgServ.warnSlide();
									}
								})
							}
						})
					}
					
				}
				,
				previewFile:function(e){
					var _btn = $(e.currentTarget)
					
					var _id = _btn.attr('aid')
					if(_id){
						var _url = '/'+init.getSite() +'/upload/previewFile.action';
						
						$.ajax({
							url:_url,
							data:{id:_id},
							success:function(data){
								var _title = $('#'+rootid + ' .modal-title')
								var _content = $('#'+rootid + ' .modal-body')
								
								if(data){
									
									if(data.archiveContent){
										//附件页面预览
										private_method.initArchiveContent(data)
									}else{
										//普通页面预览
										if(data.fileName){
											_title.text(data.fileName)
										}
										if(data.content){
											_content.append(data.content)	
										}
									}
								}
								var _m = $('#'+rootid + ' #doc-preview');
								_m.modal('show');
							}
							,
							error:function(){
								bsMsgServ.warnSlide();
							}
						})
					}
				}

			};

			
			return public_method;

		});